package by.bsuir.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import by.bsuir.entity.Node;
import by.bsuir.service.NodeService;
import by.bsuir.service.NodeServicePostgres;
import by.bsuir.util.InetScan;

/**
 * Servlet implementation class Test
 */
public class Controller extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        request.setCharacterEncoding("UTF-8");
        int firstIp = 0;
        int lastIp = 254;
        String host = request.getParameter("host");
        String login = request.getParameter("login");
        String passwd = request.getParameter("passwd");
        String domain = request.getParameter("domain");
        String search = request.getParameter("search");
        String sfirstIp = request.getParameter("firstIp");
        String slastIp = request.getParameter("lastIp");
        Node node = (Node) request.getSession().getAttribute("node");

        if (sfirstIp != null && !sfirstIp.isEmpty()) {
            firstIp = Integer.parseInt(sfirstIp);
        }
        if (slastIp != null && !slastIp.isEmpty()) {
            lastIp = Integer.parseInt(slastIp);
        }

        try {

            InetScan inetScan = new InetScan(login, passwd, domain);
            node = inetScan.scan(host);
            NodeService nodeService = new NodeServicePostgres();
            nodeService.save(node);

            request.getSession().setAttribute("host", host);
            request.getSession().setAttribute("login", login);
            request.getSession().setAttribute("passwd", passwd);
            request.getSession().setAttribute("domain", domain);
            request.getSession().setAttribute("search", search);
            request.getSession().setAttribute("firstIp", firstIp);
            request.getSession().setAttribute("lastIp", lastIp);
            request.getSession().setAttribute("node", node);
            request.getSession().setAttribute("rootNode", node);

            RequestDispatcher rd = request.getRequestDispatcher("/jsp/scan.jsp");
            rd.forward(request, response);
        } catch (Exception e) {
            throw new ServletException(e.getMessage());
        }
    }

}
